from watchlist import app,db
from flask import render_template,url_for,flash,redirect,request,abort

from watchlist.models import User,Movie
from flask_login import login_user,login_required,logout_user,current_user

@app.errorhandler(404)
def page_not_found(e):
    return render_template('error.html'), 404

## 路由函数: index,edit,delete,login,logout,settings [137- 233]
@app.route('/',methods=['GET','POST'])
def index():
    if request.method == 'POST':
        if not current_user.is_authenticated:
            return redirect(url_for('index'))
        title = request.form.get('title')
        year = request.form.get('year')

        if not title or not year or len(year) > 4 or len(title) > 60:
            flash("Invalid Input ")
            return redirect(url_for('index'))  ## 重定向
        movie = Movie(title=title,year=year)
        db.session.add(movie)
        db.session.commit()
        flash('Item Created')
        return redirect(url_for('index'))

    movies = Movie.query.all()
    return render_template('index.html', movies=movies)

@app.route('/movie/edit/<int:movie_id>',methods=['GET','POST'])
@login_required
def edit(movie_id):
    # movie = Movie.query.get_or_404(movie_id)
    movie = db.session.get(Movie, movie_id)  # 使用 Session.get() 替代 Query.get_or_404
    if not movie:
        return abort(404)  # 如果记录不存在，返回 404 错误
    if request.method == 'POST':
        title = request.form.get('title')
        year = request.form.get('year')

        if not title or not year or len(year) > 4 or len(title) > 60:
            flash("Invalid Input ")
            return redirect(url_for('edit',movie_id=movie_id))  ## 重定向
        movie.title = title
        movie.year = year
        db.session.add(movie)
        db.session.commit()
        flash('Item update')
        return redirect(url_for('index'))  ##重定向到主页面
    return render_template('edit.html', movie=movie)  ##更新编辑页面模板的内容

@app.route('/movie/delete/<int:movie_id>', methods=['POST'])  # 限定只接受 POST 请求
@login_required
def delete(movie_id):
    movie = db.session.get(Movie, movie_id)
    if not movie:
        abort(404)  # 如果记录不存在，返回 404 错误
    db.session.delete(movie)  # 删除对应的记录
    db.session.commit()  # 提交数据库会话
    flash('Item deleted.')
    return redirect(url_for('index'))  # 重定向回主页


@app.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if not username or not password:
            flash('Invalid input ')
            return redirect(url_for('login'))
        
        user = User.query.first()
        if username == user.username and user.validate_password(password):
            login_user(user)
            flash('Successful login ')
            return redirect(url_for('index'))
        
        flash('Invalid username or password ')
        return redirect(url_for('login'))
    
    return render_template('login.html')
        
@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('GoodBye ')
    return redirect(url_for('index'))

@app.route('/setting',methods=['GET','POST'])
def settings():
    if request.method == 'POST':
        name = request.form['name']

        if not name or len(name) > 20:
            flash("Invalid Input ")
            return redirect(url_for('index'))
        
        current_user.name = name
        db.session.commit()
        flash('Setting updated.')
    return render_template('setting.html')